package com.pug.zixun.auto;

import org.pug.generator.util.JDBCTypesUtils;
import org.pug.generator.util.TableInfo;
import org.pug.generator.util.Tool;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022-05-29$ 23:57$
 */

public class Test {

    // 注解 就是面向对象的注释
    public static void main(String[] args) {
        //ClassScaner.scan("com.pug.zixun.controller", RestController.class)
        //        .forEach(clazz -> System.out.println(clazz));

        List<TableInfo> tableInfos = new Test().loadTable("kss_banner");
        for (TableInfo tableInfo : tableInfos) {
            System.out.println(tableInfo);
        }
    }


    public Connection getConn() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/kss-zixun-db?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf-8&useSSL=false",
                    "root", "mkxiaoer");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<TableInfo> loadTable(String tablename) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs1 = null;
        try {
            conn = getConn();
            stmt = conn.createStatement();
            rs1 = stmt.executeQuery("SELECT * FROM " + tablename);
            ResultSetMetaData rsmd = rs1.getMetaData();
            List<TableInfo> maps = new ArrayList<>();
            Map<String, Map<String, String>> columnCommentByTableName = getColumnCommentByTableName(tablename);
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                String field = rsmd.getColumnName(i);
                int type = rsmd.getColumnType(i);//拿到数据库具体数据类型代号
                String strtype = JDBCTypesUtils.jdbcTypeToJavaType(type).getName();

                TableInfo tableInfo = new TableInfo();
                tableInfo.setColumn(field);
                tableInfo.setName(Tool.lineToHump(field));
                tableInfo.setHname(Tool.HlineToHump(field));
                tableInfo.setType(strtype);
                tableInfo.setDtype(JDBCTypesUtils.getJdbcName(type));
                tableInfo.setCtype(strtype.substring(strtype.lastIndexOf(".") + 1));
                tableInfo.setComment(columnCommentByTableName.get(field).get("comment"));
                tableInfo.setDbField(columnCommentByTableName.get(field).get("field"));
                tableInfo.setDbType(columnCommentByTableName.get(field).get("type").toLowerCase());
                tableInfo.setClen(getTypeLen(columnCommentByTableName.get(field).get("type")));
                tableInfo.setPrimarkey(columnCommentByTableName.get(field).get("iskey").equalsIgnoreCase("PRI"));
                tableInfo.setNull(columnCommentByTableName.get(field).get("isnull").equalsIgnoreCase("YES"));
                tableInfo.setDefaultVal(columnCommentByTableName.get(field).get("defaultval"));
                tableInfo.setDate(tableInfo.getCtype().equalsIgnoreCase("date"));
                maps.add(tableInfo);
            }
            return maps;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs1 != null) {
                    rs1.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }


    // 获得某表中所有字段的注释
    public Map<String, Map<String, String>> getColumnCommentByTableName(String tableName) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConn();
            stmt = conn.createStatement();
            rs = stmt.executeQuery("show full columns from " + tableName);
            System.out.println("【" + tableName + "】");
            Map<String, Map<String, String>> mapMap = new HashMap<>();
            while (rs.next()) {
                Map<String, String> map = new HashMap<>();
                map.put("field", rs.getString("Field"));
                map.put("type", rs.getString("Type"));
                map.put("isnull", rs.getString("Null"));
                map.put("iskey", rs.getString("Key"));
                map.put("defaultval", rs.getString("Default"));
                map.put("comment", rs.getString("Comment"));
                mapMap.put(rs.getString("Field"), map);
            }
            return mapMap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public static String getTypeLen(String type) {
        try {
            if (type.indexOf("date") != -1) {
                return "20";
            }
            String pattern = "\\((.+?)\\)";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(type);
            if (m.find()) {
                return m.group(1);
            }
            return "255";
        } catch (Exception e) {
            return "";
        }
    }

}
